﻿using System;
using System.Linq;

namespace RestUpMVC.Resource
{
    internal class ResourceIdentityPropertyNameResolver : IResourceMetaDataResolver
    {
        public void ResolveMetaData(Type resourceType, ResourceMetaData resourceMetaData)
        {
            if (resourceType == null) throw new ArgumentNullException("resourceType");
            if (resourceMetaData == null) throw new ArgumentNullException("resourceMetaData");

            //first look for a property marked with the ResourceIdAttribute
            var properties = resourceType.GetProperties();
            var identifierProperties = properties.Where(x => x.GetCustomAttributes(typeof(ResourceIdAttribute), true).Count() > 0).ToArray();
            if (identifierProperties.Count() > 1)
            {
                //multiple properties have the ResourceIdAttribute and cannot determine which property is the Id
                throw new ResourceIdNotFoundException();
            }

            if (identifierProperties.Count() == 1)
            {
                resourceMetaData.IdentityPropertyName = identifierProperties[0].Name;
                return;
            }

            //no properties with ResourceIdAttribute applied, look for Id properties that match the convention set in the Configuration
            var idPropertyConvention = RestUpMvcConfiguration.Instance.ResourceIdPropertyName;
            var idProperties = properties.Where(x => x.Name.Equals(idPropertyConvention, StringComparison.OrdinalIgnoreCase)).ToArray();
            if (idProperties.Count() == 0)
            {
                throw new ResourceIdNotFoundException();
            }
            if (idProperties.Count() > 1)
            {
                throw new ResourceIdNotFoundException();
            }
            resourceMetaData.IdentityPropertyName = idProperties[0].Name;
            return;
        }
    }
}